package com.okhttp.retrofit.callfactory;

import com.okhttp.utils.RetrofitLog;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.HttpUrl;
import okhttp3.Request;

/**
 * @author YLG
 * @Datetime 2020/4/21-10:48 PM
 * @Version v1.0
 * @description 根据请求头来修改baseurl值
 * <pre>
 *   retrofitBuilder.callFactory(new ReplaceBaseUrlCallFactory(OkHttpClient){
 *
 *       @Override
 *       protected HttpUrl getNewUrl(String baseUrlName, Request request) {
 *         return null;
 *       }
 *     });
 * </pre>
 */
public abstract class CallFactoryProxy implements Call.Factory {

  public static final String BASEURL_HEADER ="host-url";
  //判断URL是否以(https,http,ftp,rtsp,mms)://开头
  private static final String URL_REGEX="^((https|http|ftp|rtsp|mms)?://).*$";

  private Call.Factory mDelegate;
  private boolean enableDynamicHostUrl;

  public CallFactoryProxy(){}

  public void setCallFactory(Call.Factory delegate){
    this.mDelegate=delegate;
  }
  
  /**
   * 全局开启HostUrl动态设置，优先级较低于 {@link #BASEURL_HEADER} 配置
   * @param enable
   */
  public void enableDynamicHostUrl(boolean enable){
    this.enableDynamicHostUrl=enable;
  }
  
  private boolean isUrlValid(String url){
    if(url==null || "".equals(url)){
      return false;
    }
    Pattern p = Pattern.compile(URL_REGEX);
    return p.matcher(url).matches();
  }
  
  @Override
  public Call newCall(Request request) {
    String baseUrlName = request.header(BASEURL_HEADER);
    if (isUrlValid(baseUrlName) || enableDynamicHostUrl) {
      okhttp3.HttpUrl newHttpUrl = generateNewUrl(baseUrlName, request);
      if (newHttpUrl != null) {
        // Request newRequest = request.newBuilder().url(newHttpUrl).build();
        Request newRequest=request.newBuilder()
                             .removeHeader(BASEURL_HEADER)
                             .url(newHttpUrl)
                             .build();
        return mDelegate.newCall(newRequest);
      } else {
        RetrofitLog.e("CallFactoryProxy","New host url is null");
      }
    }
    //不修改
    return mDelegate.newCall(request);
  }
  
  /**
   *
   * @param baseUrlName 可空
   * @param request
   * @return
   */
   protected abstract HttpUrl generateNewUrl(String baseUrlName, Request request);
}
